import { createElement } from './element'
import { VNode } from './vnode';
import { isVnode } from './isType'
import { h } from './h'
//将node替换到target节点上
export function replace(target: Element, node: VNode): void {
    if (target.parentNode) {
        target.parentNode.replaceChild(createElement(node), target)
    } else {
        throw new Error('target没有父节点,没有挂载到真实dom上')
    }
}

export function mount(oldNode: VNode | Element, newNode: VNode) {
    if (!isVnode(oldNode) && oldNode instanceof Element) {
        oldNode = h(oldNode.nodeName.toLowerCase(), {}, oldNode.innerHTML, oldNode)
    }

    //如果oldNode和newNode是同一个节点就精细化比较内部节点
    if (oldNode.sel == newNode.sel && oldNode.key == newNode.key) {
        diff(oldNode as VNode, newNode)
    } else {
        //如果不是就直接替换oldNode
        replace(oldNode.ele, newNode)
    }
}

function diff(oldNode: VNode, newNode: VNode): void {
    //新节点与旧节点时同一个对象地址就直接退出不对比
    if (oldNode == newNode) return
    //当新节点是文字节点时，直接将文字节点赋值到oldNode的innerHTML上
    if (newNode.text && newNode.children == undefined || newNode.children.length == 0) {
        if (oldNode.text !== newNode.text) {
            oldNode.ele.innerHTML = newNode.text
        }
    }
    //当新节点是数组元素节点时
    else {
        //平且旧节点是文字节点时
        if (oldNode.text && oldNode.children == undefined || oldNode.children.length == 0) {
            //清空oldNode里的dom
            oldNode.ele.innerHTML = ''
            console.log(111)
            for (let i = 0; i < newNode.children.length; i++) {
                oldNode.ele.appendChild(createElement(newNode.children[i] as VNode))
            }
        }
        //新旧节点都是children数组时
        else {

        }
    }
}